<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  personalTagAdd,
  personalTagInfo,
  personalTagUpdate,
} from '#/api/company/tag/personal';
import { tagTypes } from '#/components/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import TagStylePicker from '#/views/system/dict/data/tag-style-picker.vue';

import { tagModalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '编辑标签' : '新增标签';
});

/**
 * 标签样式选择器
 * default: 预设标签样式
 * custom: 自定义标签样式
 */
const selectType = ref('default');

/**
 * 根据标签样式判断是自定义还是默认
 * @param listClass 标签样式
 */
function setupSelectType(listClass: string) {
  // 判断是自定义还是预设
  const isDefault = Reflect.has(tagTypes, listClass);
  selectType.value = isDefault ? 'default' : 'custom';
}

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: tagModalSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[650px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, tagGroupId, type } = modalApi.getData() as {
      id: number | string;
      tagGroupId: number | string;
      type: number | string;
    };
    isUpdate.value = !!id;
    await formApi.setValues({ groupId: tagGroupId, type });

    if (isUpdate.value && id) {
      const record = await personalTagInfo(id);
      setupSelectType(record.listClass);
      await formApi.setValues(record);
    }
    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // formApi.getValues拿到的是一个readonly对象，不能直接修改，需要cloneDeep
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? personalTagUpdate(data) : personalTagAdd(data));
    console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  selectType.value = 'default';
  resetInitialized();
}

/**
 * 取消标签选中 必须设置为undefined才行
 */
async function handleDeSelect() {
  await formApi.setFieldValue('listClass', undefined);
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm>
      <template #listClass="slotProps">
        <TagStylePicker
          v-bind="slotProps"
          v-model:select-type="selectType"
          :allow-clear="false"
          @deselect="handleDeSelect"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
